from flask import current_app, abort, render_template, g, request, jsonify

from info import db
from info.common import user_login_data
from info.models import News, Comment, User
from info.modules.news import news_blu

# 2.获取新闻详情  动态URL
from info.utils.response_code import RET, error_map


# 新闻详情页
@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    # 根据新闻id取出该新闻
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    # 1.查询点击量前10的新闻
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    # 2.转为字典类型
    news_list = [news.to_basic_dict() for news in news_list]

    # 点击量+1
    news.clicks += 1

    user = g.user

    is_collect = False  # 默认没有收藏
    if user:
        # 判断用户是否收藏了该新闻
        if news in user.collection_news:
            is_collect = True

    # 查询该新闻的所有评论(按生成日期倒序), 传入模版,进行渲染
    try:
        comments = news.comments.order_by(Comment.create_time.desc()).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    comment_list = []

    for comment in comments:
        comment_dict = comment.to_dict()
        is_like = False
        # 判断评论被点过赞的
        if user:  # 已经登陆
            if comment in user.like_comments:  # 如果评论已经在点赞中
                is_like = True

        # 记录当前用户是否已经被点过赞
        comment_dict["is_like"] = is_like
        comment_list.append(comment_dict)

    is_followed = False
    # 判断用户是否已经登陆,并且新闻是否一作者
    if user and news.user:
        # 查询该新闻的作者是否被用户关注
        if news.user in user.followed:
            is_followed = True

    # 3.数据进行优化处理
    user = user.to_dict() if user else None
    # 模板渲染详情页面  将新闻数据传入模板, 进行内容替换
    return render_template("news/detail.html", news=news.to_dict(), news_list=news_list, user=user,
                           is_collect=is_collect,
                           comments=comment_list, is_followed=is_followed)


# 收藏/取消收藏
@news_blu.route('/news_collect', methods=['POST', 'GET'])
@user_login_data
def news_collect():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.进行校验
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 转换news_id为整形
    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断是否收藏
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 3.根据action执行收藏/取消收藏(添加/删除)
    if action == "collect":
        # user和news建立关系
        user.collection_news.append(news)
    else:
        # user和news取消关系
        user.collection_news.remove(news)

    # 4.返回json
    return jsonify(errno=RET.OK, rrmsg=error_map[RET.OK])


# 评论和回复
@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 1.获取参数
    comment_content = request.json.get("comment")
    news_id = request.json.get("news_id")
    parent_id = request.json.get("parent_id")
    # 2.校验参数
    if not all([comment_content, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.loggner.error(e)
        return jsonify(RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 3.生成一条评论(添加评论到数据库中)
    comment = Comment()
    comment.content = comment_content
    comment.news_id = news_id
    comment.user_id = user.id
    if parent_id:
        try:
            parent_id = int(parent_id)
            comment.parent_id = parent_id
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        db.session.add(comment)
        db.session.commit()  # 这里必须手动commit, 否则主键不生成,前端获取不到该评论的id
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 4.返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=comment.to_dict())


# 点赞/取消点赞
@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 1.获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    # 2.校验参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        comment_id = int(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 3.判断该评论是否存在
    try:
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 4.根据action执行点赞/取消点赞(建立/删除关系)
    if action == "add":  # 收藏
        # user和comment建立关系
        user.like_comments.append(comment)
        # 点赞数量+1
        comment.like_count += 1
    else:
        # user和comment删除关系
        user.like_comments.remove(comment)
        # 点赞数量-1
        comment.like_count -= 1

    # 5.返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 收藏/取消收藏
@news_blu.route('/followed_user', methods=['POST', 'GET'])
@user_login_data
def followed_user():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 1.获取参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    # 2.进行校验
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 转换news_id为整形
    try:
        user_id = int(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断该作者是否存在
    try:
        author = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断是否关注
    if action not in ["follow", "unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 3.根据action执行关注/取消关注(添加/删除)
    if action == "follow":
        # user和author建立关系
        user.followed.append(author)
    else:
        # user和author取消关系
        user.followed.remove(author)

    # 4.返回json
    return jsonify(errno=RET.OK, rrmsg=error_map[RET.OK])
